package com.xingxue.module.user.controller;

import com.xingxue.module.user.entity.Paper;
import com.xingxue.module.user.entity.PaperDetail;
import com.xingxue.module.user.entity.QuestionDetail;
import com.xingxue.module.user.entity.Result;
import com.xingxue.module.user.repository.PaperRepository;
import com.xingxue.module.user.repository.QuestionDetailRepository;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class PaperController {

    @Autowired
    private PaperRepository paperRepository;

    @Autowired
    private QuestionDetailRepository questionDetailRepository;

    @PostMapping("/api/paper/{userId}/{name}/{score}")
    @ApiOperation(value = "添加试卷信息", httpMethod = "POST", produces = "application/json", consumes = "application/json")
    @Transactional
    public Result savePaper(@PathVariable @ApiParam(value = "用户编号", required = true) int userId,
                            @PathVariable @ApiParam(value = "试卷名称", required = true) String name,
                            @PathVariable @ApiParam(value = "分数", required = true) int score,
                            @RequestBody  @ApiParam(value = "试卷详情集合", required = true) List<PaperDetail> paperDetailList) {
        Paper paper = new Paper();
        paper.setUserId(userId);
        paper.setName(name);
        paper.setScore(score);
        for (PaperDetail pd : paperDetailList) {
            paper.addDetail(pd);
            QuestionDetail qd = questionDetailRepository.findByUserIdAndQuestionId(userId, pd.getQuestionId());
            if(qd != null) {
                qd.setCorrect(pd.isCorrect());
            } else {
                qd = new QuestionDetail();
                qd.setCorrect(pd.isCorrect());
                qd.setQuestionId(pd.getQuestionId());
            }
            questionDetailRepository.save(qd);
        }
        paperRepository.save(paper);
        return new Result(true, "添加试卷成功");
    }
}
